import { useCallback, useEffect, useRef, useState } from 'react';
// import Weather from '@/components/Weather/index';
import qqGroup from '@/images/xja.png';
import type { UserModelState } from '@/models/userModel';
import {
  deleteArticleSearchRecord,
  findArticleByAearchAssociatedWord,
  findArticleListByLookRecord,
  findSearchRecord,
} from '@/services/articles';
import { getScrollTop, warpTag } from '@/utils';
import { getAddress, getWeather } from '@/utils/getWeatherInfo';
import useRequest from '@ahooksjs/use-request';
import {
  DeleteOutlined,
  HomeOutlined,
  MenuFoldOutlined,
  MenuUnfoldOutlined,
  MessageOutlined,
  ToTopOutlined,
  UserOutlined,
} from '@ant-design/icons';
import type { ConnectRC } from '@umijs/max';
import { connect, history, useLocation, useModel, useSearchParams } from '@umijs/max';
import type { InputRef } from 'antd';
import {
  Avatar,
  Button,
  Col,
  Drawer,
  Empty,
  Input,
  message,
  Popover,
  Row,
  Spin,
  Tooltip,
} from 'antd';
import classnames from 'classnames';
import Login from '../Login/index';
import styles from './index.less';

const { Search } = Input;

const paginationInit = {
  current: 1,
  pageSize: 10,
};

interface PropsT {
  usermodel: UserModelState;
  loading: boolean;
}
const Index: ConnectRC<PropsT> = (props) => {
  const { dispatch } = props;
  const searchRef = useRef<InputRef>(null);
  const headerRef = useRef<HTMLDivElement>(null);
  const location = useLocation() as unknown as Location;
  const [searchVal, setSearchVal] = useSearchParams();
  const { initialState: { currentUser: { nickname = '', headPortrait = '' } = {} } = {}, refresh } =
    useModel('@@initialState');
  // 模糊搜索可选项
  const [articleList, setArticleList] = useState<ARTICLEAPI.ARTICLE[]>([]);
  const [, setWeatherStatus] = useState<`${ENUM.Weather}`>('faiWeather');
  const [open, setOpen] = useState<boolean>(false);
  const [searchInputValue, setSearchInputValue] = useState<string>('');
  // 历史搜索可选项
  const [viewList, setViewHistoryList] = useState<ARTICLEAPI.ARTICLE[]>([]);
  // 搜索历史
  const [historyList, setHistoryList] = useState<ARTICLEAPI.SearchHistoryT[]>([]);

  const { run: findArticleByAearchAssociatedWordRun } = useRequest(
    findArticleByAearchAssociatedWord,
    {
      debounceInterval: 300,
      manual: true,
      onSuccess: (res) => {
        const { code, data: { records = [] } = {}, message: errorMessage } = res;
        if (code === 200) {
          setArticleList(records);
        } else {
          message.error(errorMessage);
        }
      },
    },
  );
  // 浏览记录
  const { run: findArticleListByLookRecordRun, loading: LookRecordLoading } = useRequest(
    findArticleListByLookRecord,
    {
      debounceInterval: 500,
      manual: true,
      onSuccess: (res) => {
        const { code, data: { records = [] } = {}, message: errorMessage } = res;
        if (code === 200) {
          setViewHistoryList(records);
        } else {
          message.error(errorMessage);
        }
      },
    },
  );
  // 获取搜索历史
  const { run: findSearchRecordRun } = useRequest(findSearchRecord, {
    manual: true,
    onSuccess: (res) => {
      console.log(res);
      const { code, data: { records = [] } = {}, message: errorMessage } = res;
      console.log(records);

      if (code === 200) {
        setHistoryList(records);
      } else {
        message.error(errorMessage);
      }
    },
  });

  // 删除搜索历史记录
  const { run: deleteArticleSearchRecordRun } = useRequest(deleteArticleSearchRecord, {
    manual: true,
    onSuccess: (res) => {
      const { code, message: errorMessage } = res;
      if (code === 200) {
        message.success('删除成功!');
      } else {
        message.error(errorMessage);
      }
    },
  });

  // 固定定位
  const handleScroll = () => {
    const scrollTop = getScrollTop();
    if (scrollTop > 0) {
      headerRef.current?.classList.add(styles.headerFixed);
    } else {
      headerRef.current?.classList.remove(styles.headerFixed);
    }
  };

  // 退出登录
  const loginOut = async () => {
    localStorage.removeItem(BASE_TOKEN_NAME);
    localStorage.removeItem('blogUserInfo');
    await refresh();
  };

  // 当前用户信息
  const userContent = () => {
    return (
      <div className={styles.userInfoWrapper}>
        <div className={styles.basicInfo}>
          <div className={styles.profilePhoto}>
            <Avatar size="default" className={styles.avatar} src={headPortrait} alt="avatar" />
          </div>
          <div className={styles.nameWrapper}>
            <div className={styles.name}>昌南</div>
          </div>
        </div>
        <div className={styles.traceWrapper}>
          <div className={styles.attention}>
            <div className={styles.number}>111</div>
            <div className={styles.text}>关注</div>
          </div>
          <div className={styles.praised}>
            <div className={styles.number}>111</div>
            <div className={styles.text}>赞过</div>
          </div>
          <div className={styles.collect}>
            <div className={styles.number}>111</div>
            <div className={styles.text}>收藏</div>
          </div>
        </div>
        <div className={styles.transferWarehouseList}>
          <div className={styles.item}>
            <UserOutlined />
            <div style={{ marginLeft: '10px' }}>我的主页</div>
          </div>
          <div className={styles.item}>
            <UserOutlined />
            <div style={{ marginLeft: '10px' }}>我的足迹</div>
          </div>
          <div className={styles.item}>
            <UserOutlined />
            <div style={{ marginLeft: '10px' }}>我的主页</div>
          </div>
          <div className={styles.item}>
            <UserOutlined />
            <div style={{ marginLeft: '10px' }}>我的足迹</div>
          </div>
          <div className={styles.item}>
            <UserOutlined />
            <div style={{ marginLeft: '10px' }}>我的主页</div>
          </div>
          <div className={styles.item}>
            <UserOutlined />
            <div style={{ marginLeft: '10px' }}>我的足迹</div>
          </div>
        </div>
        <div className={styles.optionWrapper}>
          <a>我的设置</a>
          <a onClick={loginOut}>退出登录</a>
        </div>
      </div>
    );
  };

  // 关键字变色
  const warpTagHandler = useCallback(
    (param: string) => {
      if (articleList.length > 0) {
        return warpTag(param, searchRef?.current?.input?.value || '');
      }
      return '';
    },
    [articleList],
  );

  // 搜索
  const onSearch = (val: string) => {
    setSearchVal({
      searchStrM: val,
    });
    if (location.pathname !== '/search') {
      window.open(`/search?searchStrM=${val}`);
    }
  };

  useEffect(() => {
    findArticleByAearchAssociatedWordRun({
      ...paginationInit,
      articleTitle: searchInputValue,
    });
  }, [searchInputValue]);

  const tokenString = localStorage.getItem(BASE_TOKEN_NAME);

  const popoverContent = () => {
    return (
      <div className={styles.popoverContentWrapper}>
        {searchInputValue ? (
          <div className={styles.articleList}>
            {articleList.length > 0 ? (
              articleList.map((item) => {
                return (
                  <div
                    key={item.articleId}
                    className={styles.articleItem}
                    onClick={() => onSearch(item.articleTitle)}
                  >
                    <div
                      dangerouslySetInnerHTML={{
                        __html: warpTagHandler(item.articleTitle),
                      }}
                    />
                  </div>
                );
              })
            ) : (
              <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
            )}
          </div>
        ) : (
          <>
            <div className={styles.leftList}>
              {tokenString && (
                <div className={styles.toolbarSearchTitle}>
                  <div>搜索历史</div>
                  <div className={styles.tSTIcon} onClick={deleteArticleSearchRecordRun}>
                    <DeleteOutlined />
                    <span>清空</span>
                  </div>
                </div>
              )}
              <div className={styles.articleList}>
                {historyList.map((item) => {
                  return (
                    <div
                      key={item.articleSearchRecordId}
                      className={styles.articleItem}
                      onClick={() => {
                        setSearchInputValue(item.witticismContent);
                        onSearch(item.witticismContent);
                      }}
                    >
                      {item.witticismContent}
                    </div>
                  );
                })}
              </div>
            </div>
          </>
        )}
      </div>
    );
  };

  const historyPopoverContent = () => {
    const tokenString = localStorage.getItem(BASE_TOKEN_NAME);
    return (
      <div className={classnames(styles.popoverContentWrapper)} style={{ width: '300px' }}>
        {tokenString ? (
          <Spin spinning={LookRecordLoading}>
            <div
              className={classnames(styles.articleList)}
              style={{ width: '300px', minHeight: '200px' }}
            >
              {viewList.map((item) => {
                return (
                  <div
                    key={item.articleId}
                    className={styles.articleItem}
                    onClick={() => window.open(`/article/view/${item.articleId}`)}
                  >
                    {item.articleTitle}
                  </div>
                );
              })}
            </div>
          </Spin>
        ) : (
          <div className={styles.noLoginWrap}>
            <div>登录即可查看浏览历史和收藏</div>
            <Button type="primary" shape="round" block onClick={() => window.showLoginModal(true)}>
              立即登录
            </Button>
          </div>
        )}
      </div>
    );
  };

  useEffect(() => {
    (async function handle() {
      const {
        content: {
          address_detail: { adcode },
        },
      } = await getAddress();
      const { result: { now: { text = 'faiWeather' } = {} } = {} } = await getWeather(adcode);
      setWeatherStatus(text);
    })();
    window.addEventListener('scroll', handleScroll, true);
    const val = searchVal.get('searchStrM');
    if (val && location.pathname === '/search') {
      // 如果请求文章接口
      setSearchInputValue(val);
    }
    // 移除监听事件
    return window.removeEventListener('scroll', handleScroll);
  }, []);

  return (
    <div className={styles.headerWrapper}>
      <Login />
      <div className={styles.navLeftMenu}>
        <MenuUnfoldOutlined onClick={() => setOpen(true)} />
        <Drawer
          title="导航栏"
          placement="left"
          width={150}
          open={open}
          onClose={() => setOpen(false)}
          closable={false}
          extra={<MenuFoldOutlined style={{ fontSize: '24px' }} onClick={() => setOpen(false)} />}
        >
          <div className={styles.menuNavList}>
            {/*<div*/}
            {/*  className={classnames(styles.navText)}*/}
            {/*  onClick={() => window.open('/personalHomepage')}*/}
            {/*>*/}
            {/*  动态*/}
            {/*</div>*/}
            {/*<div className={styles.navText}>留言</div>*/}
            <div
              className={classnames(
                styles.navText,
                location.pathname.indexOf('/plaza') !== -1 ? styles.activateNavText : null,
              )}
              onClick={() => window.open('/plaza')}
            >
              广场
            </div>
            <div
              className={classnames(
                styles.navText,
                location.pathname.indexOf('/spice') !== -1 ? styles.activateNavText : null,
              )}
              onClick={() => window.open('/spice')}
            >
              Spice
            </div>
          </div>
        </Drawer>
      </div>
      <Row ref={headerRef} className={classnames(styles.header)}>
        <Col className={styles.navLeft}>
          {/*<div*/}
          {/*  className={classnames(*/}
          {/*    styles.navTitle,*/}
          {/*    location.pathname.indexOf('/personalHomepage') !== -1 ? styles.activateNavText : null,*/}
          {/*  )}*/}
          {/*  onClick={() => window.open('/personalHomepage')}*/}
          {/*>*/}
          {/*  动态*/}
          {/*</div>*/}
          {/*<div className={styles.navTitle}>留言</div>*/}
          <div
            className={classnames(
              styles.navTitle,
              styles.navTitleHome,
              location.pathname.indexOf('/plaza') !== -1 ? styles.activateNavText : null,
            )}
            onClick={() => history.push('/plaza')}
          >
            小记鸭
          </div>
          <div
            className={classnames(
              styles.navTitle,
              location.pathname.indexOf('/spice') !== -1 ? styles.activateNavText : null,
            )}
            onClick={() => history.push('/spice')}
          >
            Spice
          </div>
        </Col>
        <Col className={styles.searchWrapper}>
          <Popover showArrow={false} placement="bottom" content={popoverContent} trigger="focus">
            <Search
              onFocus={() => {
                if (!searchInputValue) {
                  findSearchRecordRun();
                }
              }}
              value={searchInputValue}
              ref={searchRef}
              className={styles.searchInput}
              placeholder="请输入要搜索的内容"
              onChange={(e) => {
                setSearchInputValue(e.target.value);
                if (!e.target.value) {
                  findSearchRecordRun();
                }
              }}
              onSearch={onSearch}
              enterButton
            />
          </Popover>
        </Col>
        <Col className={styles.navRight}>
          {/* <div className={styles.navTitle}>代办事项</div> */}
          <Popover placement="bottom" content={historyPopoverContent} trigger="hover">
            <div
              className={styles.navTitle}
              onMouseEnter={() => {
                const tokenString = localStorage.getItem(BASE_TOKEN_NAME);
                tokenString && findArticleListByLookRecordRun();
              }}
            >
              足迹
            </div>
          </Popover>
          <div
            className={styles.navTitle}
            onClick={() => history.push('/admin/articlemanage/articles/add')}
          >
            创作
          </div>
          {/*<div className={styles.navTitle}>相册</div>*/}
          <div className={classnames(styles.personalOperation)}>
            {!nickname ? (
              <div
                className={styles.notLogin}
                onClick={() =>
                  dispatch({ type: 'usermodel/changeIsShowLoginModal', payload: true })
                }
              >
                请登录
              </div>
            ) : (
              <Popover placement="bottomRight" content={userContent()} trigger="click">
                <Avatar size="small" className={styles.avatar} src={headPortrait} alt="avatar" />
              </Popover>
            )}
          </div>
        </Col>
      </Row>
      {/* <OperationBall /> */}
      <div className={styles.floatBtn}>
        <span>
          <Tooltip
            placement="left"
            color="#fff"
            getPopupContainer={(triggerNode) => triggerNode}
            title={<img className={styles.qqGroup} src={qqGroup} />}
          >
            <MessageOutlined />
          </Tooltip>
        </span>
        <span onClick={() => window.scrollTo(0, 0)}>
          <ToTopOutlined />
        </span>
        <span>
          <HomeOutlined
            onClick={() => {
              history.push('/plaza');
            }}
          />
        </span>
      </div>
    </div>
  );
};
export default connect(({ usermodel }: { usermodel: UserModelState }) => ({
  usermodel,
}))(Index);
